package com.qcheng.diangpingclient;

import com.example.diangpingclient.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.qcheng.fragment.FragmentHome;
import com.qcheng.fragment.FragmentMy;
import com.qcheng.fragment.FragmentSearch;
import com.qcheng.fragment.FragmentTuan;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MainActivity extends FragmentActivity implements
		android.widget.RadioGroup.OnCheckedChangeListener {
	@ViewInject(R.id.main_content_tabs)
	private RadioGroup radioGroup;
	@ViewInject(R.id.main_home)
	private RadioButton mainHome;
	@ViewInject(R.id.main_my)
	private RadioButton mainMy;
	@ViewInject(R.id.main_tuangou)
	private RadioButton mainTuan;
	@ViewInject(R.id.main_search)
	private RadioButton mainSearch;
	@ViewInject(R.id.main_content)
	// 管理Fragment
	private FragmentManager fragmentManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		ViewUtils.inject(this);

		// 初始化Fragment
		fragmentManager = getSupportFragmentManager();
		// 设置默认选中
		mainHome.setChecked(true);
		radioGroup.setOnCheckedChangeListener(this);
		// 切換不同的Fragment
		changeFragment(new FragmentHome(), false);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	/**
	 * 切換不同的Fragment
	 * 
	 * @param frament
	 * @param isFirst
	 */
	@SuppressLint("Recycle")
	public void changeFragment(Fragment frament, boolean isInit) {
		// 开启事务
		FragmentTransaction transaciton = fragmentManager.beginTransaction();
		transaciton.replace(R.id.main_content, frament);
		if (isInit) {
			transaciton.addToBackStack(null);
		}
		transaciton.commit();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		switch (checkedId) {
		case R.id.main_home:
			changeFragment(new FragmentHome(), true);
			break;
		case R.id.main_my:
			changeFragment(new FragmentMy(), true);
			break;
		case R.id.main_search:
			changeFragment(new FragmentSearch(), true);
			break;
		case R.id.main_tuangou:
			changeFragment(new FragmentTuan(), true);
			break;

		default:
			break;
		}
	}

}
